-- 定义插件任务
task("rswin32")
do
  -- 设置类别为插件
  set_category("plugin")
  -- 设置插件菜单
  set_menu({
    usage = "xmake rswin32 [target]",
    description = "Generate a rust win32 project, based on windows-sys.rs",
    options = {
      { nil, "target", "v", nil, "a00" },
    },
  })

  -- 插件运行入口
  on_run(function()
    import("core.base.option")

    -- 获取目标项目名称，默认为 "a00"
    local target_name = option.get("target") or "a00"
    print("生成项目: %s", target_name)
    local project_root = path.join(os.curdir(), target_name)

    -- 定义项目目录结构
    local project_dirs = {
      path.join(project_root, "src"),
    }

    -- 创建目录
    for _, dir in ipairs(project_dirs) do
      os.mkdir(dir)
      print("创建目录: %s", dir)
    end

    local cargo_toml_content = string.format(
      [[# Rust Win32
[package]
name = "%s"
version = "0.1.0"
edition = "2024"

[dependencies.windows-sys]
version = "0.61.2"
features = [
    "Win32_Graphics_Gdi",
    "Win32_System_LibraryLoader",
    "Win32_UI_WindowsAndMessaging",
    "Win32_UI_Controls",
]
    ]],
      target_name
    )
    local cargo_toml_file = path.join(project_root, "Cargo.toml")
    io.writefile(cargo_toml_file, cargo_toml_content)
    print("生成文件: %s", cargo_toml_file)

    local gitignore_content = [[/target]]
    local gitignore_file = path.join(project_root, ".gitignore")
    io.writefile(gitignore_file, gitignore_content)
    print("生成文件: %s", gitignore_file)

    local main_rs_content = [[use windows_sys::{
    Win32::Foundation::*, Win32::Graphics::Gdi::*, Win32::System::LibraryLoader::GetModuleHandleW,
    Win32::UI::Controls::*, Win32::UI::WindowsAndMessaging::*, core::*,
};

fn instance() -> HMODULE {
    unsafe { GetModuleHandleW(core::ptr::null()) }
}

fn main() {
    unsafe {
        let window_class = w!("window");

        // 填充窗口类结构体
        let wc = WNDCLASSW {
            hCursor: LoadCursorW(core::ptr::null_mut(), IDC_ARROW),
            hInstance: instance(),
            lpszClassName: window_class,
            style: CS_HREDRAW | CS_VREDRAW,
            lpfnWndProc: Some(wndproc),
            cbClsExtra: 0,
            cbWndExtra: 0,
            hIcon: core::ptr::null_mut(),
            hbrBackground: core::ptr::null_mut(),
            lpszMenuName: core::ptr::null(),
        };

        // 注册窗口类
        let atom = RegisterClassW(&wc);
        debug_assert!(atom != 0);

        // 创建窗口
        let window = CreateWindowExW(
            0,
            window_class,
            w!("这是一个简单的窗口"),
            WS_OVERLAPPEDWINDOW | WS_VISIBLE,
            CW_USEDEFAULT,
            CW_USEDEFAULT,
            CW_USEDEFAULT,
            CW_USEDEFAULT,
            core::ptr::null_mut(),
            core::ptr::null_mut(),
            instance(),
            core::ptr::null(),
        );
        debug_assert!(!window.is_null());

        // 显示窗口
        ShowWindow(window, SW_SHOW);
        UpdateWindow(window);

        // 消息循环
        let mut message = std::mem::zeroed();
        while GetMessageW(&mut message, core::ptr::null_mut(), 0, 0) != 0 {
            TranslateMessage(&message);
            DispatchMessageW(&message);
        }
    }
}

extern "system" fn wndproc(window: HWND, message: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
    unsafe {
        match message {
            WM_PAINT => {
                println!("WM_PAINT");
                let mut ps = PAINTSTRUCT::default();
                let hdc = BeginPaint(window, &mut ps);
                // TODO: 这里可以进行绘制操作
                let sys_brush = GetSysColorBrush(COLOR_WINDOW);
                FillRect(hdc, &ps.rcPaint, sys_brush);
                EndPaint(window, &ps);
                0
            }
            WM_DESTROY => {
                println!("WM_DESTROY");
                PostQuitMessage(0);
                0
            }
            _ => DefWindowProcW(window, message, wparam, lparam),
        }
    }
}]]
    local main_rs_file = path.join(project_root, "src", "main.rs")
    io.writefile(main_rs_file, main_rs_content)
    print("生成文件: %s", main_rs_file)

    os.runv("git", { "init", project_root })

    print("项目 '%s' 生成成功！", target_name)
    print("项目结构：")
    print("  " .. target_name .. "/")
    print("  ├── .git/")
    print("  ├── src/")
    print("  │   └── main.rs")
    print("  ├── .gitignore")
    print("  ├── Cargo.toml")
    print("接下来，你可以：")
    print("  - 进入项目目录: cd " .. target_name)
    print("  - 使用 cargo 构建运行: cargo run")
  end)
end
